package debby.com.lifecycle

import android.os.SystemClock
import androidx.lifecycle.ViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
import java.util.*
import kotlin.collections.HashMap


/**
 * Created by debby on 2019/1/28.
 * 描述:
 */
class MyViewModel : ViewModel() {
    private lateinit var mElapsedTime: MutableLiveData<Long>

    private lateinit var inputData: MutableLiveData<HashMap<Int, String>>


    fun getElapsedTime(): LiveData<Long> {
        if (!::mElapsedTime.isInitialized) {
            mElapsedTime = MutableLiveData()
            loadData()
        }
        return mElapsedTime
    }

    fun getInputData(): LiveData<HashMap<Int, String>> {
        if (!::inputData.isInitialized) {
            inputData = MutableLiveData()
        }
        return inputData
    }

    fun setInputData(key: Int, data: String) {
        if (inputData.value == null) {
            inputData.value = HashMap()
        }
        inputData.value!![key] = data
    }


    fun changeData() {
        mElapsedTime.value = 18120
    }

    private fun loadData() {
        val mInitialTime = SystemClock.elapsedRealtime()
        val timer = Timer()
        timer.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                val newValue =
                    (SystemClock.elapsedRealtime() - mInitialTime) / 1000;
                // setValue() 不能再后台线程调用，所以使用post到主线程
                mElapsedTime.postValue(newValue);
            }
        }, 1000, 1000)
    }


}